import { Component } from '@angular/core';
import { Events, AlertController, App, List, ModalController, NavController, NavParams } from 'ionic-angular';
import { AuthorizationDetailService } from './detail.service';
import { Config } from '../../../providers/config';
import { Common } from '../../../providers/common';
import { ContactChoosePage } from '../../contact/choose/choose.component';
import { SysDirPage } from './sysDir.component';
import { AuthorizationListPage } from '../list/list.component';
import { Storage } from '@ionic/storage';

import _ from 'lodash';

@Component({
  selector: 'page-authorization-detail',
  templateUrl: './detail.html',
  providers: [AuthorizationDetailService]
})
export class AuthorizationDetailPage {
	moa_page_name: any = "page-authorization-detail";
	moa_page_explain = "";

  // 缓存通过组织树选择的人员
  // 结构如下：
  // [{
  //   empid:"A938493525",
  //   name:"冯镜蒯",
  //   orgid:"xtyfz",
  //   loginid:"fengjk",
  //   titleid:"ybyg"
  // },{}]
  defaultEmpByTree = [];

  // 明细信息对象
  item = {
    "authorized": "",
    "authorizedName": "",
    "edate": "",
    "empid": "",
    "empidName": "",
    "module": "",
    "moduleName": "",
    "numb": "",
    "sdate": "",
    "stat": "",
    "type": ""
  }

  //  授权开始日期
  sdate;
  // 授权开始时间
  sdateTime
  // 授权结束日期
  edate;
  // 授权结束时间
  edateTime

  // add 新增， update 编辑 ，detail详情
  type;
  // 标题，公共一个页面
  title = {
    "add": "增加授权配置",
    "update": "编辑授权配置",
    "detail": "授权配置详细"
  }

  // 当前登录人empid
  empid;
  // 当前登录人姓名
  name;

  // 如果是编辑页面，页面不可以编辑
  isDetail = false;

  // 系统目录树
  defaultDirByTree;

  // 缓存开始结束时间
  startTime;
  endTime;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public detailService: AuthorizationDetailService,
    private navParams: NavParams,
    public config: Config,
    public storage: Storage,
    public common: Common,
    public events: Events
  ) {

    var that = this;

    // 获得当前登录人ID
    this.storage.get('userInfo').then(function(userInfo) {
      if (userInfo) {
        that.empid = userInfo.empid;
        that.name = userInfo.emname;
      }
      return;
    }).then(function() {
      that.type = that.navParams.get("type");
      that.moa_page_explain = that.title[that.type];

      if (that.type == "update") { // 更新
        var detailObj = that.navParams.get("item");
        that.item.authorized = detailObj["authorized"];
        that.item.authorizedName = detailObj["authorizedName"];

        that.edate = _.split(detailObj["edate"], " ")[0];
        that.edateTime = _.split(detailObj["edate"], " ")[1];
        that.sdate = _.split(detailObj["sdate"], " ")[0];
        that.sdateTime = _.split(detailObj["sdate"], " ")[1];

        that.item.empid = detailObj["empid"];
        that.item.empidName = detailObj["empidName"];
        that.item.module = detailObj["module"];
        that.item.numb = detailObj["numb"];
        that.item.moduleName = detailObj["moduleName"];
        that.item.stat = detailObj["stat"];
        that.item.type = detailObj["type"];
        that.formateDefaultEmpByTree();
      } else if (that.type == "add") { //新增
        that.item.empid = that.empid;
        that.item.empidName = that.name;
        that.item.stat = "STAR";
        that.item.type = "ALL";

        // 初始化时间
        that.sdate = common.getDate(0);
        that.sdateTime = common.getT();
        that.edate = that.sdate;
        that.edateTime = that.sdateTime;

        that.item.sdate = that.sdate + " " + that.sdateTime;
        that.item.edate = that.edate + " " + that.edateTime;

      } else if (that.type == "detail" || that.type == "detialHis") { // 详情
        var detailObj = that.navParams.get("item");
        that.item.authorized = detailObj["authorized"];
        that.item.authorizedName = detailObj["authorizedName"];
        that.item.edate = detailObj["edate"];
        that.item.empid = detailObj["empid"];
        that.item.empidName = detailObj["empidName"];
        that.item.module = detailObj["module"];
        that.item.numb = detailObj["numb"];
        that.item.moduleName = detailObj["moduleName"];
        that.item.sdate = detailObj["sdate"];
        that.item.stat = detailObj["stat"];
        that.item.type = detailObj["type"];
        that.formateDefaultEmpByTree();
        that.isDetail = true;

        that.endTime = detailObj["edate"]; // 缓存时间
        that.startTime = detailObj["sdate"]; // 缓存时间
      }
    })
  }

  /**
   * [submit 提交]
   * @param {[type]} type [save 保存修改; insert提交新增]
   */
  submit(type) {
    var currTime = this.common.getTime(0); // 当前系统时间
    // 新增授权，如果开始时间小于当前系统提时间，则将当前系统时间设置为开始时间
    if(type =="insert" && this.item.sdate < currTime) {
      this.item.sdate = currTime;
    }

    var checkNotNullMsg = this.checkNotNull();
    var checkTimeMsg = this.checkTime();
    // 校验信息  非空-》开始时间不能大于结束时间
    var checkMsg = checkNotNullMsg == "" ? (checkTimeMsg == "" ? "" : checkTimeMsg) : checkNotNullMsg;

    if (checkMsg != "") { // 数据校验
      let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
        title: "提示",
        message: checkMsg,
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
    } else {
      // 如果付的是全部子系统权限，清空子模块ID和名称
      if (this.item.type == 'ALL') {
        this.item.moduleName = "";
        this.item.module = "";
      }

      if (type == "save") { // 保存修改
        this.save();
      } else if (type == "insert") { // 提交新增
        this.insert();
      }
    }

  }


  /**
   * [save 保存]
   */
  save() {
    console.log("##authorization.save 更新对象");
    console.log(this.item);

    this.detailService.updateAuthorization(this.item).subscribe(data => {
      if (data["code"] == "0") {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "保存成功",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                if (this.endTime == this.item.edate && this.startTime == this.item.sdate) { // 时间有变化
                  this.events.publish("authorization-list-doRefresh", { "type": "update", "item": this.item });
                } else { // 时间没有变化
                  this.events.publish("authorization-list-doRefresh", null);
                }

                this.navCtrl.pop();
              }
            }
          ]
        });
        alert.present();
      } else {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "保存失败",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  /**
   * [insert 新增]
   */
  insert() {
    console.log("##authorization.insert 新增对象");
    console.log(this.item);

    this.detailService.insertAuthorization(this.item).subscribe(data => {
      if (data["code"] == "0") {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "新增成功",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                this.events.publish("authorization-list-doRefresh", null);
                this.navCtrl.pop();
              }
            }
          ]
        });
        alert.present();
      } else {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "新增失败",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  /**
   * [delete 删除]
   */
  delete() {
    console.log("##authorization.delete 删除对象");
    console.log(this.item);

    this.detailService.deleteAuthorization(this.item.numb).subscribe(data => {
      if (data["code"] == "0") {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "删除成功",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
                this.events.publish("authorization-list-doRefresh", { "type": "delete", "item": this.item });
                this.navCtrl.pop();
              }
            }
          ]
        });
        alert.present();
      } else {
        let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
          title: "提示",
          message: "删除失败",
          buttons: [
            {
              text: "确定",
              role: 'cancel',
              handler: () => {
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  /**
   * [edit 编辑页面]
   */
  edit() {
    // 结束日期、时间
    this.edate = _.split(this.item.edate, " ")[0];
    this.edateTime = _.split(this.item.edate, " ")[1];
    // 开始日期、时间
    this.sdate = _.split(this.item.sdate, " ")[0];
    this.sdateTime = _.split(this.item.sdate, " ")[1];

    this.isDetail = false;
    this.type = "update";
  }

  /**
   * [cancle 返回上一个页面]
   */
  cancle(type) {
    if (type == "add") {
      this.navCtrl.pop(); // 新增页面点取消，回到列表
    } else if (type == "update") { // 编辑页面点取消，回到详情页面
      this.type = "detail";
      this.isDetail = true;
    }
  }

  // 校验字段不能为空
  checkNotNull() {
    var retMsg = "";
    if (this.item.authorized == "") {
      retMsg = "请选择要授权的人";
    } else if (this.item.stat == "") {
      retMsg = "请选择授权状态";
    } else if (this.item.type == "") {
      retMsg = "请选择授权类型";
    } else if (this.item.moduleName == "" && this.item.type == "MODU") {
      retMsg = "请选择授权子系统";
    }

    return retMsg;
  }

  ionChange(){
    this.item.sdate = this.sdate + " " + this.sdateTime;
    this.item.edate =  this.edate + " " + this.edateTime
  }

  // 校验开始时间不能大于结束时间
  checkTime() {
    var retMsg = "";
    if (this.item.sdate >= this.item.edate) {
      retMsg = "结束时间必须大于开始时间";
    }

    return retMsg;
  }

  /**
   * [formateDefaultEmpByTree 格式化被授权人,主要为与通讯录交换数据]
   */
  formateDefaultEmpByTree() {
    var authorizedList = _.split(this.item.authorized, ",");
    var authorizedNameList = _.split(this.item.authorizedName, ",");

    var zipped = _.zip(authorizedList, authorizedNameList);
    var that = this;
    _.forEach(zipped, function(data) {
      let temp = _.zipObject(['empid', 'name'], data);
      that.defaultEmpByTree.push(temp);
    })
  }


  ionViewDidLoad() {
    //this.app.setTitle('DemoDetail');
  }

  /**
   * [chooseEmp 选择人员]
   * @param {[type]} item [description]
   */
  chooseEmp(item) {
    console.log("##authorization.detail.chooseEmpnames 选择外出人员");
    let that = this;
    let modal = this.modalCtrl.create(ContactChoosePage, {
      selected: this.defaultEmpByTree,
      isSelectUser: true,
      isSelectOne: true
    });

    modal.present();
    modal.onWillDismiss((data: any[]) => {
      //console.info(data);
      if (data) {
        that.defaultEmpByTree = data;
        this.item.authorized = _.toString(_.map(data, "empid")); // 外出人员用empid, 流程节点选择人用loginid
        this.item.authorizedName = _.toString(_.map(data, "name"));
      }
    });
  }

  /**
   * [chooseSys 选择子系统]
   */
  chooseSys() {
    console.log("##authorization.detial.chooseSys :" + this.item.module);
    this.detailService.getDirDir().subscribe(data => {
      let modal = this.modalCtrl.create(SysDirPage, { "module": this.item.module });

      modal.present();
      modal.onWillDismiss((data: any[]) => {
        if (data) {
          this.item.module = data["module"];
          this.item.moduleName = data["moduleName"];
        }
      });
    })
  }

}
